package hy.service.impl;

import hy.beans.Perms;
import hy.beans.Role;
import hy.beans.User;
import hy.dao.UserDao;
import hy.service.UserService;
import hy.util.PassUtil;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class)
public class UserServiceImpl implements UserService {
    @Autowired
	UserDao userDao;
 
	public void regist(User u) {
		//使用盐值
		String salt = PassUtil.randomSalt();
		System.out.println(u);
		u.setPassword(PassUtil.encode(u.getPassword(), salt));
		u.setSalt(salt);
		
		userDao.insert(u);
	}
	//登录不再由dao实现，交给shiro实现
	public void login(String username,String password) {
		User u=userDao.selectUser(username);
		if(u==null){
			System.out.println("-----------用户名不正确------------");
			throw new UnknownAccountException("用户名不正确");
		}
 
        /*数据库中的密码*/
		String dbPass = u.getPassword();
		String salt = u.getSalt();
 
		String tmp = PassUtil.encode(password,salt);
		if(!tmp.equals(dbPass)){
			throw new IncorrectCredentialsException("密码错误");
		}
	}
 
	@Override
	public List<Role> findRolesByUserName(String username) {
		return userDao.selectRolesByUserName(username);
	}
 
	@Override
	public List<Perms> findPermsByRoleId(Integer id) {
		return userDao.selectPermsByRoleId(id);
	}
}